import React, { Component } from 'react';
import { notification } from 'antd';
import { connect } from 'dva';
import { getToken } from '@/utils/authority';

@connect(({ user }) => ({
  currentUser: user.currentUser,
}))
export default class ChildIframe extends Component {
  constructor(props) {
    super(props);

    // 子模块消息
    this.onReceiveMessage = (e) => {
      if (this.props.url.indexOf(e.origin) === -1) return;
      if (e.data === '1006') {
        // token失效
        this.props.dispatch({ type: 'login/logout' });
        return;
      }
      if (e.data === 'getToken') {
        // 获取token
        document
          .getElementById(this.props.id)
          .contentWindow.postMessage({ type: 'token', data: getToken() }, e.origin);
        return;
      }
      if (e.data.type === 'Notice') {
        // 消息展示
        const noticeType = e?.data?.notice?.type;
        notification[noticeType] && notification[noticeType](e.data.notice);
      }
    };
  }
  componentDidMount() {
    window.addEventListener('message', this.onReceiveMessage);
  }
  componentWillUnmount() {
    window.removeEventListener('message', this.onReceiveMessage);
  }

  render() {
    return (
      <div
        style={{
          width: '100%',
          height: '100%',
          'padding-top': 'var(--global_HeaderBarHei)',
          overflow: 'hidden',
        }}
      >
        <iframe
          id={this.props.id}
          border={0}
          frameBorder="no"
          src={this.props.url}
          width="100%"
          height="100%"
        />
      </div>
    );
  }
}
